package com.ztesoft.zcm.cmdb.util;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import io.fabric8.kubernetes.api.model.Node;
import io.fabric8.kubernetes.api.model.NodeList;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;

import com.ztesoft.zsmart.core.log.ZSmartLogger;
import com.ztesoft.zsmart.zcm.core.boot.autoconfigure.kubernetes.KubeClientConfig;


/**
 * Created by Administrator on 2017/6/27 0027.
 */
@Service
public class K8sApiHelper {
    private static final ZSmartLogger logger = ZSmartLogger.getLogger(K8sApiHelper.class);

    @Autowired
    private KubeClientConfig kubeClientConfig;

    /**
     * cachedK8sClient
     */
    private Map<String, KubernetesClient> cachedK8sClient = new HashMap<String, KubernetesClient>();

    /**
     * getClient
     *
     * @param masterUrl masterUrl
     * @return KubernetesClient
     */
    public KubernetesClient getClient(String masterUrl) {
        KubernetesClient client = cachedK8sClient.get(masterUrl);
        if (client == null) {
            if (masterUrl != null) {
                client = new DefaultKubernetesClient(kubeClientConfig.createKubeConfig(masterUrl));
                cachedK8sClient.put(masterUrl, client);
            }
        }
        if (client == null) {
            throw new RuntimeException("can't create KubernetesClient for masterUrl " + masterUrl);
        }
        else {
            return client;
        }
    }

    public Boolean cordonNode(String masterUrl, String nodeName) {
        Node node = getClient(masterUrl).nodes().withName(nodeName).get();
        node.getSpec().setUnschedulable(true);
        Node changedNode = getClient(masterUrl).nodes().withName(nodeName).patch(node);
        return changedNode.getSpec().getUnschedulable();
    }

    public Boolean uncordonNode(String masterUrl, String nodeName) {
        Node node = getClient(masterUrl).nodes().withName(nodeName).get();
        node.getSpec().setUnschedulable(false);
        Node changedNode = getClient(masterUrl).nodes().withName(nodeName).patch(node);
        return changedNode.getSpec().getUnschedulable();
    }

    public NodeList getNode(String masterUrl) {
        return getClient(masterUrl).nodes().list();
    }

    public void addK8sNodeLable(String masterApi, String ip, Map<String, String> labels) {
        getClient(masterApi).nodes().withName(ip).edit().editMetadata()
                .addToLabels(labels).endMetadata().done();
    }

    public void removeK8sNodeLable(String masterApi, String ip, Map<String, String> labels) {
        getClient(masterApi).nodes().withName(ip).edit().editMetadata()
                .removeFromLabels(labels).endMetadata().done();
    }

}
